using System;
using System.Collections.Generic;

namespace Commons.Collections
{
	[Serializable]
	public class TypeDictionary<C>
	{
		private Dictionary<Type,C> _cached;
		private List<C> _values;

		public TypeDictionary()
		{
			_cached = new Dictionary<Type, C>();
			_values = new List<C>();
		}

		public bool ContainsType(Type target)
		{
			return _cached.ContainsKey(target);
		}

		public void Add(C val)
		{
			_cached[val.GetType()] = val;
			_values.Add(val);
		}

		public C Get<T>()
		{
			if (!ContainsType(typeof(T)))
			{
				foreach (C value in _cached.Values)
				{
					if (value is T)
					{
						return _cached[typeof(T)] = value;
					}
				}

				return default(C);
			}
			
			return _cached[typeof(T)];
		}

		public object Get(Type type)
		{
			if (!ContainsType(type))
			{
				foreach (C value in _cached.Values)
				{
					if (value.GetType() == type)
					{
						_cached[type] = value;
						return value;
					}
				}

				return null;
			}

			return _cached[type];
		}

		public IEnumerable<C> Values
		{
			get { return _values; }
		}
	}
}
